﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlackBird.Models;
using System.Web.UI;
using BlackBird.DataAccess;
using BlackBird.ControllerHelpers;
using BlackBird.Resources;
using BlackBird.Repositories;

namespace BlackBird.Controllers
{
	public partial class BiJiaDanController : Controller
    {
        //
        // GET: /BiJiaDan/

        const int defaultSupplierCount = 7;
        const int defaultProductCount = 50;

		private static object locker = new object();

		public virtual ActionResult Index()
        {
            return View();
        }

		[HttpGet]
        public virtual PartialViewResult NewBiJiaDan(string ParentId)
		{
            return PartialView(MVC.BiJiaDan.Views.NewBiJiaDan, new NewBiJiaDan() {Name="默认比价单", ParentId = ParentId });
		}

		/// <summary>
		/// 通过NewBijiaDan提供的商品数和供应商数创建比价单
		/// </summary>
		/// <param name="bijiadan"></param>
		/// <returns></returns>
		[HttpPost]
		[OutputCache(Location = OutputCacheLocation.None)]
		public virtual ActionResult NewBiJiaDan(NewBiJiaDan bijiadan)
		{
            bijiadan.ProductCount = bijiadan.ProductCount < 10 ? 10 : bijiadan.ProductCount + 10;
            bijiadan.SupplierCount = defaultSupplierCount;

			return RedirectToAction("CreateBiJiaDan", "BiJiaDan", bijiadan);
		}

		[HttpGet]
		[OutputCache(Location = OutputCacheLocation.None)]
		public virtual ActionResult CreateBiJiaDan(NewBiJiaDan bijiadan)
		{
			int nCompayCount = bijiadan.SupplierCount > 0 ? bijiadan.SupplierCount : 3;
			int nProductCount = bijiadan.ProductCount > 0 ? bijiadan.ProductCount: 30;

            BiJiaDanTableDM oT = BiJiaDanDataAccess.CreateDefaultTable(nCompayCount, nProductCount);
            BiJiaDanDM bDm = new BiJiaDanDM() 
			{ 
				table = oT, 
				ParentId = bijiadan.ParentId, 
				Name = bijiadan.Name,
				CurrentStepNumber = 0,
                Status = SupportTypeStatus.CaoGao
			};

            //Create Bijiadan in DB
            bDm.Date = DateTime.Today;
            bDm.CreateUserName = AccountHelper.GetCurrentUser(this).DisplayName;

			//if there are more than one thread to create the bianhao
			//maybe there are some conflick. so locker it here
			lock (locker)
			{
				bDm.BianHao = BiJiaDanHelper.GetBiJiaDanBianHao(bijiadan.ParentId);
				string id = BiJiaDanDataAccess.CreatBiJiaDan(bDm, this);
			}

            //Add Bijiadan to Project
            ProjectDataAccess.AddBijiaDanToProject(bDm.ParentId, bDm.Id);

            //return View(MVC.BiJiaDan.Views.BiJiaDan, bDm);
            return RedirectToAction(MVC.BiJiaDan.GetBiJiaDan(bDm.Id));
		}

		[HttpGet]
		[OutputCache(Location = OutputCacheLocation.None)]
		public virtual ActionResult GetBiJiaDan(string Id)
		{
            //Get bijiadan from DB
            var bijiadan = BiJiaDanDataAccess.GetBiJiaDan(Id);

			//加入比价单相关的附件。
			var bijiadanAttachedFiles = FuJianDataAccess.GetBiJiaDanAttachedFile(int.Parse(Id), this);
			if (bijiadanAttachedFiles != null)
			{
				bijiadan.AttachedFileList = new AttachedFileList()
				{
					AttachedFiles = bijiadanAttachedFiles
				};
			}

            UpdateViewDataAtRuntime(bijiadan);

            return View(MVC.BiJiaDan.Views.BiJiaDan, bijiadan);
		}

		/// <summary>
		/// Get bijiadan attached file
		/// </summary>
		/// <param name="Id"></param>
		/// <returns></returns>
		[HttpGet]
		public virtual ActionResult GetBiJiaDanAttachedFile(string Id)
		{
			var bijiadanAttachedFiles = FuJianDataAccess.GetBiJiaDanAttachedFile(int.Parse(Id), this);
			AttachedFileList attachedFiles = null;
			if (bijiadanAttachedFiles != null)
			{
				attachedFiles = new AttachedFileList()
				{
					AttachedFiles = bijiadanAttachedFiles
				};
			}

			return PartialView(MVC.Shared.Views.Util.AttachedFileListView, attachedFiles);
		}

        public bool CanOperateBijiadan(int currentStepNumber)
        {
            var currentUser = AccountHelper.GetCurrentUser(this);
            return QuanXianAndProcessHelper.IsEnableToOperation(SupportTypes.BiJiaDan, currentUser, currentStepNumber); 
        }

        /// <summary>
        /// Update some view data at runtime
        /// </summary>
        private void UpdateViewDataAtRuntime(BiJiaDanDM bijiadan)
        {
            //can operate
            bool canOperate = QuanXianAndProcessHelper.IsEnableToOperationBiJiaDan(this, bijiadan.CurrentStepNumber);
            ViewData["isReadOnly"] = !canOperate;

            //is cai gou yuan
            var caigouyuanGroup = QuanXianAndProcessHelper.GetFirstStepGroup();
            var isCaigouyuan = QuanXianAndProcessHelper.IsThisGroup(AccountHelper.GetCurrentUser(this), caigouyuanGroup);
            ViewData["isCaigouyuan"] = isCaigouyuan;
        }

        #region Save/Submit/Close Handler
        [HttpPost]
        [OutputCache(Location = OutputCacheLocation.None)]
        public virtual ActionResult ResolveBiJiaDan(BiJiaDanDM dm)
        {
            //get the button user click
            string clickButton = Request.Form["Action"];
            var bijiadan = BiJiaDanDataAccess.GetBiJiaDan(dm.Id);

            //Handle bijiadan acccording to the button user click
            if (clickButton == BBStrings.Save)
            {
                SaveBiJiaDan(dm);
                BiJiaDanDataAccess.SaveToDatabase(bijiadan);
                return RedirectToAction(MVC.BiJiaDan.GetBiJiaDan(bijiadan.Id));
            }
			else if (clickButton == BBStrings.Submit)
			{
				return SubmitBiJiaDan(dm);
			}
			else if (clickButton == BBStrings.Cancel)
			{
				//TODO, Set the BiJiaDan Status to Cancel.
				//设置比价单的状态为 Cancel 就可以 如果没有Cancel，而直接删掉表，会引起编号重复
				return new ContentResult { Content = "Cancel BiJiaDan, we need set the bijiadan status to cancel" };
			}
            else if (clickButton == BBStrings.GuiDang)
            {
                bijiadan.Status = SupportTypeStatus.GuiDang;
                BiJiaDanDataAccess.SaveBijiadanSatusToDatabase(bijiadan);
            }
            else if (clickButton == BBStrings.ZuoFei)
            {
                bijiadan.Status = SupportTypeStatus.ZuoFei;
                BiJiaDanDataAccess.SaveBijiadanSatusToDatabase(bijiadan);
            }
			else //complete
			{
				//nothing to do
			}

            return RedirectToAction(MVC.Home.Index());
        }

        public virtual ActionResult SaveBiJiaDan(BiJiaDanDM model)
        {
            //MVC.BiJiaDan.Views.BiJiaDan includes a partialview MVC.Shared.Views.BiJiaDan.BiJiaDanTable
            //each one has their own model type
            //so here need to collect the model data twice

            //build tabel data
            BiJiaDanTableDM bijiadanTable = (BiJiaDanTableDM)DependencyResolver.Current.GetService(typeof(BiJiaDanTableDM));
            UpdateModel(bijiadanTable);

            //build bijiadan data
            BiJiaDanDM bijiadanDM = (BiJiaDanDM)DependencyResolver.Current.GetService(typeof(BiJiaDanDM));
            UpdateModel(bijiadanDM);
            bijiadanDM.table = bijiadanTable;

            //get the status posted from page
            bijiadanDM.Status = model.Status;

            //update db
            BiJiaDanDataAccess.UpdateBiJiaDan(bijiadanDM);

            return RedirectToAction(MVC.BiJiaDan.GetBiJiaDan(model.Id));
        }

        public virtual ActionResult SubmitBiJiaDan(BiJiaDanDM dm)
        {
            //1) save the bijiadan data first
            SaveBiJiaDan(dm);

            //2) update status accordingly
            var bijiadan = BiJiaDanDataAccess.GetBiJiaDan(dm.Id);
            //更新参数，状态
            GoToNextStep(bijiadan);

            //TODO: 权限检测！！！

            //cai gou can't go to shenhe page
            //if (new UserRepository().GetRoles(User.Identity.Name).Contains(RoleType.CaiGou))
            //{
            //    BiJiaDanDataAccess.SaveToDatabase(bijiadan);
            //    return RedirectToAction(MVC.Home.Index());
            //}

            //based on user's selection adjust the status accoringly under Shenghe page
            if (dm.CurrentPostComment != null)
            {
                UpdateComment(dm.CurrentPostComment);
                bijiadan.Comments.Add(dm.CurrentPostComment);

                if (dm.CurrentPostComment.Operation == ShenHeResult.Fail)
                    ResetBijiadanStatus(bijiadan);
                else if (dm.CurrentPostComment.Operation == ShenHeResult.ZuoFei)
                    bijiadan.Status = SupportTypeStatus.ZuoFei;
                //通过


                //单独保存当前comment
                ShenheDataAccess.SaveBijiadanSheheToDatabase(dm.Id, dm.CurrentPostComment);
            }

            //3) Update Bijiadan again
            BiJiaDanDataAccess.UpdateBiJiaDan(bijiadan);

            BiJiaDanDataAccess.SaveToDatabase(bijiadan);

			return RedirectToAction(MVC.BiJiaDan.GetBiJiaDan(dm.Id));
		}

        public void GoToNextStep(BiJiaDanDM dm)
        {
            //normally the status is ShengHeZhong when submit bijiadan at the first time
            if (dm.Status == SupportTypeStatus.CaoGao)
                dm.Status = SupportTypeStatus.ShengHeZhong;

			//version 1
            //var potentialStepNumber = dm.CurrentStepNumber + 1;

			//version 2 begin
			var currentUser = AccountHelper.GetCurrentUser(this);
			int maxStep = QuanXianAndProcessHelper.GetUserMaxStepNumber(currentUser, SupportTypes.BiJiaDan);
			var potentialStepNumber = maxStep + 1;
			//version 2 end

            var isValid = QuanXianAndProcessHelper.IsStepNumberAvailable(SupportTypes.BiJiaDan, potentialStepNumber);
            if (isValid)
                dm.CurrentStepNumber = potentialStepNumber;
            else
            {
                //-1 means complete
                dm.CurrentStepNumber = -1;
                dm.Status = SupportTypeStatus.ShenHeWanCheng;
            }
        }

        public void ResetBijiadanStatus(BiJiaDanDM dm)
        {
            dm.Status = SupportTypeStatus.CaoGao;
            dm.CurrentStepNumber = 0;
        }

        public void UpdateComment(CommentDM commentDm)
        {
            commentDm.UserName = AccountHelper.GetCurrentUser(this).Name;
            commentDm.Date = DateTime.Now;
        }
        #endregion
 
        #region For AutoComplete
        [HttpGet]
        public virtual ActionResult GetAllProducts()
        {
            return this.Json(BiJiaDanHelper.AllProductInformationList(), JsonRequestBehavior.AllowGet);
            //return this.Json(MockupDataStore.AllProductsDM(), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public virtual ActionResult GetProductUnit(string productName)
        {
            return this.Json(BiJiaDanHelper.ProductUnit(productName), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public virtual ActionResult GetAllSuppliers()
        {
            return this.Json(BiJiaDanHelper.AllCompanyInformationList(), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public virtual ActionResult GetSupplier(string supplierName)
        {
            return this.Json(BiJiaDanHelper.FindSupplier(supplierName), JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
